package com.gui.listeners;

import com.util.LayoutCards;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * CustomTreeListener is a customized listener class for the a JTree.
 * @author sithum
 */
public class CustomTreeListener implements TreeSelectionListener {

    private JTree tree;
    private JPanel cards;

    public CustomTreeListener(JTree tree, JPanel cards) {
        this.tree = tree;
        this.cards = cards;
    }

    public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) this.getTree().getLastSelectedPathComponent();
        if (node == null) {
            return;
        }
        Object nodeInfo = node.getUserObject();
        if (node.isLeaf()) {
            this.displayCard(LayoutCards.valueOf(nodeInfo.toString().toUpperCase()).getPanelName());
        }
    }

    /**
     * Displays the relevant panel according to the user selection.
     * @param java.lang.String panelName - Name of the displaying panel.
     */
    private void displayCard(String panelName) {
        CardLayout layout = (CardLayout) cards.getLayout();
        layout.show(cards, panelName);
    }

    /**
     * @return the tree
     */
    public JTree getTree() {
        return tree;
    }

    /**
     * @param tree the tree to set
     */
    public void setTree(JTree tree) {
        this.tree = tree;
    }

    /**
     * @return the cards
     */
    public JPanel getCards() {
        return cards;
    }

    /**
     * @param cards the cards to set
     */
    public void setCards(JPanel cards) {
        this.cards = cards;
    }
}
